package com.wstuo.md5.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;

import org.apache.log4j.Logger;

import com.wstuo.md5.action.TestMain;

/**
 * 版权MD5加密Service类
 * @author Administrator
 *
 */
public class CopyrightMD5Service implements ICopyrightMD5Service {
	private static final String JAAS_PATH = Thread.currentThread()
			.getContextClassLoader().getResource("").getPath();
	private static final Logger LOGGER = Logger.getLogger(CopyrightMD5Service.class ); 
	public static String getJasperPath() {
		return JAAS_PATH;
	}

	/**
	 * 对文件全文生成MD5摘要
	 * 
	 * @param file
	 *            要加密的文件
	 * @return MD5摘要码
	 */

	static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
			'9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wstuo.md5.service.ICopyrightMD5Service#getMD5(java.io.File)
	 */
	private String getMD5(File file) {
		String value = null;
		FileInputStream fis = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer = new byte[2048];
			int length = -1;
			@SuppressWarnings("unused")
			long s = System.currentTimeMillis();
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
			}
			byte[] b = md.digest();
			value = byteToHexString(b);
			// 16位加密
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		} finally {
			try {
				if(fis!=null){
					fis.close();
				}
			} catch (IOException ex) {
				LOGGER.error(ex.getMessage());
			}
		}
		return value;
	}

	/**
	 * 把byte[]数组转换成十六进制字符串表示形式
	 * 
	 * @param tmp
	 *            要转换的byte[]
	 * @return 十六进制字符串表示形式
	 */
	private String byteToHexString(byte[] tmp) {
		String s;
		// 用字节表示就是 16 个字节
		char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
		// 所以表示成 16 进制需要 32 个字符
		int k = 0; // 表示转换结果中对应的字符位置
		for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
			// 转换成 16 进制字符的转换
			byte byte0 = tmp[i]; // 取第 i 个字节
			str[k++] = hexdigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
			// >>> 为逻辑右移，将符号位一起右移
			str[k++] = hexdigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
		}
		s = new String(str); // 换后的结果转换为字符串
		return s;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wstuo.md5.service.ICopyrightMD5Service#JudgeMD5()
	 */
	public String JudgeMD5() {
		String login = TestMain.readValue(JAAS_PATH + "md5/md5.properties", "login");
		String index = TestMain.readValue(JAAS_PATH + "md5/md5.properties", "index");
		String setting = TestMain.readValue(JAAS_PATH + "md5/md5.properties", "setting");
		String value = null;
		if (getMD5(
				new File(JAAS_PATH.substring(0, JAAS_PATH.length() - 16)
						.replaceAll("%20", " ") + "pages/login.jsp")).equals(
				login)
				&& getMD5(
						new File(JAAS_PATH
								.substring(0, JAAS_PATH.length() - 16)
								.replaceAll("%20", " ")
								+ "pages/index.jsp")).equals(index)
				&& getMD5(
						new File(JAAS_PATH
								.substring(0, JAAS_PATH.length() - 16)
								.replaceAll("%20", " ")
								+ "pages/setting.jsp")).equals(setting)) {
			value = "correct";
		} else {
			value = "Error";
		}
		return value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wstuo.md5.service.ICopyrightMD5Service#JudgeMD5save()
	 */
	public String JudgeMD5save() {
		File f = new File(JAAS_PATH + "md5/md5.properties");
		FileWriter fw = null;
		String value = null;
		try {
			fw = new FileWriter(f);
			fw.write("");
			fw.write("login="
					+ getMD5(new File(JAAS_PATH.substring(0,
							JAAS_PATH.length() - 16).replaceAll("%20", " ")
							+ "pages/login.jsp"))
					+ "\r\nindex="
					+ getMD5(new File(JAAS_PATH.substring(0,
							JAAS_PATH.length() - 16).replaceAll("%20", " ")
							+ "pages/index.jsp"))
							+ "\r\nsetting="
							+ getMD5(new File(JAAS_PATH.substring(0,
									JAAS_PATH.length() - 16).replaceAll("%20", " ")
									+ "pages/setting.jsp")));
			
			value = "write Success";
		} catch (IOException e) {
			value = "write Error";
		} finally {
			try {
				if(fw!=null){
					fw.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);			}
		}
		return value;
	}
}
